<?php

namespace app\admin\controller\system;

use app\admin\logic\system\OssLogic;
use app\Request;
use think\App;

/**
 * 上传类
 *
 */
class UploadController extends BaseController
{
    private $ossPath = '';
    public function __construct(App $app)
    {
        parent::__construct($app);
        $pathArr = [
            'upload', 'admin', date('Y'), date('m'),
        ];
        $this->ossPath = implode('/', $pathArr);
    }

    public function index(Request $request) {
        try {
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('img_upload');

            // 上传到本地服务器
            $path = \think\facade\Filesystem::disk('public')->putFile('topic', $file);
            $path = str_replace('\\', '/', $path);
            $path = '/storage/' . $path;
            return $this->setSuccess($path);
        } catch (\Throwable $e) {
            return $this->setError($e->getMessage());
        }
    }

    public function oss(Request $request) {
        $file = $request->file('img_upload');
        if(!$file) {
            return $this->setError('没有文件上传');
        }

        $res = false;

        $bucket = config('oss.bucket'); // bucket
        $ossPath = $this->ossPath . '/' . date('d') . '_' . time() . randStr() . '.' . $file->getOriginalExtension(); // oss 地址
        $localPath = $file->getRealPath(); // 文件内容

        // 非正式环境,走内容上传.否则,走路径上传
        if(env('env', 'local') != config('business.env_production')) {
            $content = file_get_contents($localPath);
            $res = OssLogic::publicUploadContent($bucket, $ossPath, $content);
        } else {
            $res = OssLogic::privateUpload($bucket, $ossPath, $localPath);
        }


        if(!$res) {
            return $this->setError('上传失败');
        }
        return $this->setSuccess($ossPath);
    }
}